﻿using System.Collections.Generic;
using BitButterECS.Event;
using BitButterECS.Event.EventArgs;

namespace BitButterECS.Component
{
    public class ComponentManager
    {
        ComponentManager() { }
        
        public static ComponentManager Instance => Nested.instance;

        class Nested
        {
            static Nested() { }
            internal static readonly ComponentManager instance = new ComponentManager();
        }

        public BaseComponent this[int index]
        {
            get
            {
                if (ComponentCollection.ContainsKey(index))
                {
                    return ComponentCollection[index];
                }
                return null;
            }
        }

        public int AddComponent(BaseComponent component)
        {
            if (!component.IsManaged)
            {
                component.ID = currentID;
                currentID += 1;

                ComponentCollection.Add(component.ID, component);
                AddComponentEvent.RaiseEvent(this, new AddComponentEventArgs());

                return component.ID;
            }
            return -1;
        }

        public void RemoveComponent(BaseComponent component)
        {
            if (component.IsManaged)
            {
                ComponentCollection.Remove(component.ID);
                component.ID = -1;
                RemoveComponentEvent.RaiseEvent(this, new RemoveComponentEventArgs());
            }
        }

        public bool HasComponent(int id)
        {
            return componentCollection != null ? componentCollection.ContainsKey(id) : false;
        }

        //public void Reset()
        //{
        //    foreach (BaseComponent component in ComponentCollection.Values)
        //    {
        //        component.Reset();
        //    }
        //}

        Dictionary<int, BaseComponent> ComponentCollection
        {
            get
            {
                if (componentCollection == null)
                {
                    componentCollection = new Dictionary<int, BaseComponent>();
                }
                return componentCollection;
            }
        }

        Dictionary<int, BaseComponent> componentCollection;
        int currentID = 0;
    }
}
